import functools
from .store import Store

class App:
    def __init__(
            self, 
            io=(input, functools.partial(print, end="")),
            store=None):
        self._in, self._out = io
        self._store = store
        self._quit = False
        self._articles = []
        self._aid = None

    def list(self):
        self._articles = self._store.list()
        res = ["Articles:\n"]
        for i in range(len(self._articles)):
            v = self._articles[i]
            res.append(f'{i + 1}. {v["name"]} ({v["category"]}.{v["order"]})\n')
        res.append("> ")
        self._out(''.join(res))

    def run(self):
        self.list()
        while not self._quit:
            cmd = self._in()
            self._dispatch(cmd)
        self._out('Bye!\n')

    def _dispatch(self, cmd):
        cmd, *args = cmd.split(' ')
        executor = getattr(self, f'cmd_{cmd}', None)
        if executor is None:
            self._out(f'Invalid command: {cmd}.')
            return
        executor(*args)

    def cmd_quit(self):
        self._quit = True

    def cmd_use(self, id):
        self._aid = int(id) - 1
        self._out(self._articles[self._aid]['name'] + '> ')

